import express from 'express'

import matchRoute from './matchRoute'
import renderTag from './renderTag'
import renderHtml from './renderHtml'
import renderRoot from './renderRoot'
import configureStore from '../redux/configureStore'
import createReducer from '../redux/createReducer'

const renderMiddleware = ({ App, actions, routes }) => {
  const router = express.Router()
  const rootReducer = createReducer(actions)

  router.use((req, res) => {
    // console.log('------', loadData)

    const lang = req.query.lang || 'zh_CN'
    const store = configureStore(rootReducer, { lang })
    const context = {}
    const route = matchRoute(store, req, routes)

    Promise.all(route.tasks).then(() => {
      const extractor = renderTag()
      const content = renderRoot({ Component: App, url: req.originalUrl, context, store, extractor })
      const html = renderHtml({ content, state: store.getState(), entry: route.entry, extractor })
      res.send(html)
    }).catch(err => {
      res.send(err)
      console.log(err)
    })

  })

  return router
}

export default renderMiddleware